package com.gaosai.staff.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 文件工具类，缓存是把一个String写入文件 等功能
 * @author willis
 *
 */

public class FileUtils {

	/**
	 * 读取一个文本文件的内容
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String readTextFile(File file) throws IOException {

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(new FileInputStream(file), "UTF-8"));
		StringBuffer sb = new StringBuffer();
		String line;
		if (bufferedReader != null) {
			while ((line = bufferedReader.readLine()) != null) {
				sb.append(line);
			}
			bufferedReader.close();
		}
		return sb.toString();
	}

	/**
	 * 写入一个文本文件
	 * 
	 * @param file
	 * @param data
	 * @throws IOException
	 */
	public static void writeTextFile(File file, String data) throws IOException {
		try {
			if (data != null) {
				FileOutputStream fout = new FileOutputStream(file);
				fout.write(data.getBytes());
				fout.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 根据一个字节输入流返回一个字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] getInputStream(InputStream inputStream)
			throws Exception {
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		byte buffer[] = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(buffer)) != -1) {
			arrayOutputStream.write(buffer, 0, len);
		}
		arrayOutputStream.close();
		inputStream.close();
		return arrayOutputStream.toByteArray();
	}
	
	 public static long getFileSize(String path) {
	        if (StringUtils.isBlank(path)) {
	            return -1;
	        }

	        File file = new File(path);
	        return (file.exists() && file.isFile() ? file.length() : -1);
	    }
}
